import { Icon, useCall, useFieldCtx } from '@/components';
import { INPUT_KEYS } from '@/constants/componentKeys';
import { FormulaConfig } from '@/pages/components';
import { forkHandler, pick } from '@/utils';
import { Button, Input } from 'antd';
import * as PropTypes from 'prop-types';
import React, { useContext, useLayoutEffect, useRef } from 'react';
import { Context } from '.';

function Child({ onClick, value, ...props }) {
  const button = <Button type='text' size='small' onClick={onClick} icon={<Icon type='setting' />} />;
  const inputOnClick = useCall(forkHandler(() => props.readOnly, onClick, true));

  const inputRef = useRef();
  const composingRef = useRef(false);
  useLayoutEffect(() => {
    if (composingRef.current) return;
    if (!inputRef.current?.input) return;
    if (!inputRef.current.state?.value) return
    const inputValue = inputRef.current.state?.value;
    if (`${inputValue}` !== `${value}`) {
      inputRef.current.setState((v) => ({ ...v, value }));
    }
  }, [value]);
  const onInput = useCall(
    forkHandler((e) => {
      composingRef.current = e.nativeEvent.isComposing;
    }, props.onInput),
  );
  const onBlur = useCall(
    forkHandler((e) => {
      composingRef.current = false;
    }, props.onBlur),
  );

  return (
    <Input
      ref={inputRef}
      {...props}
      defaultValue={value}
      addonAfter={button}
      onClick={inputOnClick}
      onInput={onInput}
      onBlur={onBlur}
    />
  );
}

function FormulaConfigInput(props) {
  const { onChange, dutyCode = null, formulaType = 'file', fileType, value, className, style, ...rest } = props;
  const { label } = useFieldCtx('itemProps');
  const { productCode } = useContext(Context);
  const relationCode = dutyCode ? [productCode, dutyCode].join('_') : productCode;
  const inputValue = (formulaType === 'file' ? value?.costCalculateFormula?.formulaExpression : value) ?? '';
  const [inputProps, componentProps] = pick(rest, INPUT_KEYS);

  const readOnly = formulaType === 'file';

  const inputOnChange = useCall((e) => {
    // if (e.nativeEvent.isComposing === true) return;
    if (!readOnly) onChange?.(e.target.value);
  });

  return (
    <FormulaConfig
      {...componentProps}
      {...{ [formulaType === 'file' ? 'formulaData' : 'formulaValue']: value }}
      type={formulaType}
      fileType={fileType}
      relationCode={relationCode}
      onOk={onChange}
    >
      <Child
        placeholder={label ? `请选择${label}` : null}
        {...inputProps}
        value={inputValue}
        readOnly={readOnly}
        onChange={inputOnChange}
      />
    </FormulaConfig>
  );
}

FormulaConfigInput.propTypes = {
  onChange: PropTypes.any,
  dutyCode: PropTypes.any,
  formulaType: PropTypes.string,
  fileType: PropTypes.any,
  value: PropTypes.any,
  className: PropTypes.any,
  style: PropTypes.any,
};

export default FormulaConfigInput;
